// Implementation of the ServerSocket class

#include "ServerSocket.h"
#include "SocketException.h"
#include "ServerThread.h"

#include <iostream>

ServerSocket::ServerSocket (ThreadPriority pri, string _name, int port,MemoryMaps * localData ):
Thread(pri, _name)
{
	_mmapRef = localData;
  if ( ! Socket::create() )
    {
      throw SocketException ( "Could not create server socket." );
    }

  if ( ! Socket::bind ( port ) )
    {
      throw SocketException ( "Could not bind to port." );
    }

  if ( ! Socket::listen() )
    {
      throw SocketException ( "Could not listen to socket." );
    }

}

ServerSocket::~ServerSocket()
{
}

void ServerSocket::run()
{
	//_localData->showData();
	while (true) {

				// Allocate a new ServerSocket for each Client
				ServerSocket *new_sock = new ServerSocket();

				// Wait for a client to connect
				accept(*new_sock);

				ServerT * sThread = new ServerT(Thread::PRIORITY_NORMAL, "ServerThread", new_sock,_mmapRef);
				sThread->start();
				std::cout << "Thread started....\n";

				//_localData->showData();
				sleep(1);
			}
}

const ServerSocket& ServerSocket::operator << ( const std::string& s ) const
{
  if ( ! Socket::send ( s ) )
    {
      throw SocketException ( "Could not write to socket." );
    }

  return *this;

}


const ServerSocket& ServerSocket::operator >> ( std::string& s ) const
{
  if ( ! Socket::recv ( s ) )
    {
      throw SocketException ( "Could not read from socket." );
    }

  return *this;
}

void ServerSocket::accept ( ServerSocket& sock )
{
  if ( ! Socket::accept ( sock ) )
    {
      throw SocketException ( "Could not accept socket." );
    }
}

void ServerSocket::send( const std::string& s ) const
{
  if ( ! Socket::send ( s ) )
    {
      throw SocketException ( "Could not write to socket." );
    }
  }


int ServerSocket::recv ( std::string& s )
{
	int cnt = Socket::recv ( s );
	if (cnt == 0)
    {
      throw SocketException ( "Could not read from socket." );
    }

  return cnt;
}

int ServerSocket::recv2(unsigned char * buffer)
{
	return  Socket::recv2(buffer);

}

